package com.max.sportmanage.service.impl;

import com.max.sportmanage.common.Result;
import com.max.sportmanage.config.security.service.UserDetailServiceImpl;
import com.max.sportmanage.entity.SysUser;
import com.max.sportmanage.mapper.SysUserMapper;
import com.max.sportmanage.service.SysUserService;
import com.max.sportmanage.util.TokenUitl;
import com.max.sportmanage.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: sport-manage-java
 * @description:
 * @author: max-qaq
 * @create: 2021-10-19 11:23
 **/
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Resource
    SysUserMapper sysUserMapper;

    @Autowired
    UserDetailServiceImpl userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    TokenUitl tokenUitl;

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    /**
     * 登录接口
     * @param loginVo
     * @return
     */
    @Override
    public Result login(LoginVo loginVo) {
        log.info("1.开始登录");
        //加载用户名
        UserDetails userDetails = userDetailsService.loadUserByUsername(loginVo.getUsername());
        log.info("2.判断用户是否存在,密码是否正确");
        if (null == userDetails || !passwordEncoder.matches(loginVo.getPassword(),userDetails.getPassword())){
            return Result.AUTH_ERROR("账号或密码错误");
        }

        log.info("3.判断是否启用");
        if (!userDetails.isEnabled()){
            return Result.FAIL("该账号已禁用");
        }

        log.info("登录成功,在security对象中传入登录信息");
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        log.info("根据登录信息获取token");
        //借助jwt生成token
        String token = tokenUitl.generateToken(userDetails);
        Map<String,String> map = new HashMap<>(2);
        map.put("tokenHead",tokenHead);
        map.put("token",token);
        return Result.SUCCESS(map);
    }

    /**
     * 根据用户名获取用户信息
     * @param username
     * @return
     */
    @Override
    public SysUser getByUserName(String username) {
        return sysUserMapper.findByUsername(username);
    }


}
